package org.sjs.dreamfly.widget

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.RelativeLayout
import org.sjs.dreamfly.common.base.Listener
import org.sjs.dreamfly.common.base.ListenerOwner
import org.sjs.dreamfly.common.util.LogUtil
import java.lang.ref.WeakReference

class LockContainer: RelativeLayout, ListenerOwner<LockContainer.OnTouchListener> {
    interface OnTouchListener: Listener {
        override fun notify(vararg params: Any?) {
            val array = params[0] as Array<*>
            onTouch(array[0] as LockContainer, array[1] as MotionEvent)
        }
        fun onTouch(view: LockContainer, event: MotionEvent)
    }
    override val listeners = mutableListOf<WeakReference<OnTouchListener>>()
    constructor(context: Context) : this(context, null, -1, -1)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, -1, -1)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : this(context, attrs, defStyleAttr, -1)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)

    private var locked = false
//    private val touchListeners = mutableListOf<((event: MotionEvent)->Boolean)>()

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        return if (locked) {
            if (ev?.action == MotionEvent.ACTION_DOWN) super.onInterceptTouchEvent(ev)
            else true
        } else {
            super.onInterceptTouchEvent(ev)
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        LogUtil.d("action:${event?.action}")
        if (event?.action == MotionEvent.ACTION_UP) {
            notifyListeners(this@LockContainer, event)
        }
        return locked
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        return super.dispatchTouchEvent(ev)
    }

    fun lock() {
        locked = true
    }

    fun unLock() {
        locked = false
    }
}